package com.polaris.live.viewmodel.party

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.network.HTTP_SUCCESS_CODE
import com.polaris.live.constant.LiveConst
import com.polaris.live.net.liveService
import com.polaris.live.resp.go_resp.LiveIdBean
import com.polaris.live.viewmodel.party.base.BasePartyActivityModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

/**
 * PartyAnchorModel  主播Model
 * @author Created by 天晴 on 2024/2/24 11:15
 * @since 1.0.0
 **/
class PartyAnchorModel : BasePartyActivityModel(){

    //直播心跳
    val liveHeartbeatLiveData = MutableLiveData<Boolean>()
    private var liveHeartbeatFailureCount = 0
    private var liveHeartbeatJob: Job? = null
    fun launchLiveHeartbeat(liveId: Long) {
        liveHeartbeatFailureCount = 0
        liveHeartbeatJob = viewModelScope.launch {
            try {
                while (isActive) {
                    liveHeartbeatFailureCount = try {
                        val resp = liveService.liveCheck(LiveIdBean(liveId))

                        if (resp.code == HTTP_SUCCESS_CODE) {
                            0
                        } else {
                            if (resp.code == CommonConst.ErrorCode.LIVE_NOT_EXIST) {
                                Int.MAX_VALUE
                            } else {
                                liveHeartbeatFailureCount + 1
                            }
                        }
                    } catch (_: Throwable) {
                        liveHeartbeatFailureCount + 1
                    }

                    if (liveHeartbeatFailureCount >= 3) {
                        liveHeartbeatLiveData.value = true
                    }

                    delay(LiveConst.HEARTBEAT_TIME)
                }
            } finally {
                if (liveHeartbeatJob == coroutineContext[Job]) {
                    liveHeartbeatJob = null
                }
            }
        }
    }
}